import { Context } from 'egg';

export default function adminAuth() {
  return async function adminAuthMiddleware(ctx: Context, next: () => Promise<any>) {
    // 获取token
    const token = ctx.get('authorization')?.replace('Bearer ', '') || ctx.query.token;
    const decoded:any = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
    ctx.state.user = decoded;
    if (!decoded || !token) {
      ctx.body = { success: false, code: 401, message: '未登录或登录已过期' };
      return;
    }
    if (!decoded?.is_admin) {
      ctx.body = { code: 403, message: '无权限访问' };
      return;
    }

    await next();
  };
}